<?php
	/**
	 * Web service requested by the autosuggest JS
	 * http://www.brandspankingnew.net/specials/ajax_autosuggest/ajax_autosuggest_autocomplete.html
	 * returns suggested book name, author, collection, edition, isbn
	 */

	session_start();
	include_once "includes/db.inc";
	
	$dbFields =	array(
		'liv_nom' => 'nom',
		'liv_auteur' => 'auteur',
		'liv_ISBN' => 'ISBN',
		'liv_ed' => 'edition',
		'liv_col' => 'collection'
	);
	
	header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
	header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
	header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 
	header ("Pragma: no-cache"); // HTTP/1.0	
	
	$input = mysql_real_escape_string (strtolower(trim($_GET['q'])));
	if (empty($input) || !isset($dbFields[$_GET['f']])) {
		header('HTTP/1.0 400 Bad Request', true, 400);
		exit();
	}
	
	header("Content-Type: application/json");
	$caseInsensitiveResults = array();
	$limit = 10;
	if (isset($_GET['limit']))
		$limit = (int) $_GET['limit'];
	if (($limit < 1) || ($limit > 15) )
		$limit = 15;
	$field = $dbFields[$_GET['f']];
	$query = "SELECT distinct($field) FROM `livres` WHERE $field LIKE '%$input%' LIMIT $limit";
	$result = biblio_db_query($query);
	echo '{"results": [';
	if ($result !== FALSE) {
		$i = 0;
		while ($row = biblio_db_fetch_array($result)) {
			$l = strtolower($row[$field]);
			if (in_array($l, $caseInsensitiveResults))
				continue;
			$caseInsensitiveResults[] = $l;
			// escape \ and "
			$value = str_replace(array('\\', '"'), array('\\\\', '\\"'), $row[$field]);
			if ($i > 0)
				echo ', ';
			echo '{"id":'.$i++.', "value": "'.utf8_encode($value).'", "info": ""}';
		}
	}
	echo "]}";
?>